//获取应用实例
var app = getApp();
const $ = require('../../utils/utils');
const config = require('../../config');
const wallet = require('../../manager/walletManager.js')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        borrowList: [],
        oper: "0",//“0”-我在读; “1”-读完了
        pageno: 1,
        pagesize: 10,
        hasMoreData: true,
        isLogin: false,
        isLoadingData: false,


        // 购买相关
        isShowPayModule: false,
        isShowCouponModule: false,
        payImgSrc: '../../img/vipIconImg.png',
        payImgSrcNor: '../../img/selNor.png',
        cash_amount: '',
        extra_amount: '0.00',
        cashIndex: true,
        preparBookInfo: {},
        coupon_id: null,
        couponList: [],
        orderTransId: ''
    },

    /***************life Cycle *******************/
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        if (!$.isNullOrEmpty(options) && !$.isNullOrEmpty(options.tab)) {
            // 从“我的”页面的
            this.setData({ 'oper': options.tab })
        }



        this.setData({
            cash_amount: wx.getStorageSync('cash_amount')
        })

        if (parseFloat(this.data.cash_amount) <= 0) {
            this.setData({
                cashIndex: false
            })
        }



        this.current_read_list();
    },
    onShow: function () {

        let login = wx.getStorageSync("isLogin")
        this.setData({
            isLogin: login
        });
    },

    /************Methods **************************/
    buyPictureBook: function (e) {
        console.log(e)
        let that = this
        let book = e.currentTarget.dataset.book

        this.setData({
            isShowPayModule: true,
            orderTransId: book.orderTransId
        })

        let params = {
            orderTransId: book.orderTransId,
            isbn: book.isbn,
            userid: wx.getStorageSync('userid'),
            usertoken: wx.getStorageSync('usertoken'),
        }
        console.log(params)
        $.post(config.prepareBuyBook, params).then(data => {
            console.log('prepareBuyBook', data)
            that.setData({
                preparBookInfo: data.detail,
                coupon_id: data.detail.coupon_id,
                extra_amount: data.detail.extra_amount
            })
            let dataparams = {
                oper: 3,
                bookcaseId: data.detail.bookcaseId,
                userid: wx.getStorageSync('userid'),
                usertoken: wx.getStorageSync('usertoken'),
            }
            let url = $.getUrl(config.getCouponList, dataparams);
            $.get(url).then(data => {
                console.log(data)
                that.setData({
                    couponList: data.items
                })
            }).catch(error => {

            })
        }).catch(error => {

        })

    },

    payForPictureBook: function () {
        let that = this
        let params = {
            charge_code: this.data.preparBookInfo.pay_amount,
            charge_type: 1,
            coupon_id: this.data.coupon_id == null ? '' : that.data.coupon_id,
            orderTransId: this.data.orderTransId,
            pay_amount: this.data.extra_amount
        }

        wallet.paymentV2(params).then(data => {
            console.log(data)
            that.current_read_list()
            that.setData({
                isShowPayModule: false
            })
            $.goto(config.page.buy_book_success)
        }).catch(error => {

        })

    },

    dismissPayModule: function () {
        this.setData({
            isShowPayModule: false
        })
    },

    showCouponList: function () {
        this.setData({
            isShowCouponModule: true
        })
    },

    dismissCouponModule: function () {
        this.setData({
            isShowCouponModule: false
        })
    },

    confirmCoupon: function () {
        wx.showModal({
            title: '提示',
            content: '您当前没有可用的优惠券',
            showCancel: false,
            confirmColor: '#FF3B30',
        })
    },

    blockTapAction: function () {

    },

    blockMoveAction: function () {

    },

    chooseChargeType: function (e) {
        let chargeType = Number(e.currentTarget.dataset.chargetype)
        this.setData({
            extra_amount: '0.00',
            cashIndex: chargeType
        })
        this.calcPayAmount()
    },

    selectedCoupon: function (e) {
        console.log("#selectedCoupon()", e.currentTarget.dataset.coupon)
        let that = this
        let coupon = e.currentTarget.dataset.coupon
        this.setData({
            coupon_id: coupon.coupon_id
        })
        this.calcPayAmount()
    },

    donotUseCoupon: function () {
        console.log("#donotUseCoupon()")
        let that = this
        this.setData({
            coupon_id: null
        })

        this.calcPayAmount()
    },

    calcPayAmount: function () {
        let that = this
        let params = {
            coupon_id: this.data.coupon_id == null ? '' : that.data.coupon_id,
            amount: this.data.preparBookInfo.pay_amount,
            oper: 4,
        }

        if (this.data.cashIndex) {
            params.cash_amount = this.data.preparBookInfo.cash_amount
        }

        wallet.calcPayAmount(params).then(data => {
            that.setData({
                extra_amount: data.detail.extra_amount
            })
        }).catch(error => {

        })
    },

    enterBookDetail: function (e) {
        console.log('detail', e)
        let isbn = e.currentTarget.dataset.isbn
        let url = config.page.bookDetail + '?book_isbn=' + isbn
        $.goto(url)
    },

    // 扫码按钮响应函数
    scanCode: function () {
        console.log(`#borrow_list_scanCode()`)
        wx.setStorageSync("scanIsFromBorrowList", true)
        if (!wx.getStorageSync("isLogin")) {

            if (e.detail.errMsg == 'getPhoneNumber:ok') {
                app.aesPhoneNumber(e.detail.iv, e.detail.encryptedData).then(data => {
                    app.scanCode();
                })
            } else if (e.type == "getphonenumber") {
                app.scanCode();
            }
        } else {
            app.scanCode();
        }

    },

    // 当前阅读列表
    current_read_list: function () {
        var that = this;
        that.setData({
            oper: "0",
            pageno: 1,
            borrowList: [],
            isLoadingData: true
        });
        that.getBorrowList();
    },

    // 读完列表
    already_read_list: function () {
        var that = this;
        that.setData({
            oper: "1",
            pageno: 1,
            borrowList: [],
            isLoadingData: true
        });
        that.getBorrowList();
    },

    // 已购列表
    already_buy_list: function () {
        var that = this;
        that.setData({
            oper: "2",
            pageno: 1,
            borrowList: [],
            isLoadingData: true
        });
        that.getBorrowList();
    },

    // 获取书库列表接口
    getBorrowList: function () {
        wx.showLoading({
            title: '借阅信息查询中...',
            mask: true,
        })
        let params = {
            userid: wx.getStorageSync('userid'),
            usertoken: wx.getStorageSync('usertoken'),
            oper: this.data.oper,
            pageno: this.data.pageno,
            pagesize: this.data.pagesize
        }
        let url = $.getUrl(config.getBorrowList, params)
        $.get(url).then(data => {
            console.log(data)
            wx.hideLoading();
            var contentlistTem = this.data.borrowList;
            var contentlist = data.items;
            if (contentlist.length < this.data.pagesize) {
                this.setData({
                    borrowList: contentlistTem.concat(contentlist),
                    isLoadingData: false,
                    hasMoreData: false
                })
            } else {
                this.setData({
                    isLoadingData: false,
                    borrowList: contentlistTem.concat(contentlist),
                    hasMoreData: true,
                });
            }
        })

    },

    //  监听用户向上滑动
    onReachBottom: function () {
        console.log('onReachBottom');
        var that = this;
        if (that.data.hasMoreData) {
            that.setData({
                pageno: that.data.pageno + 1
            })
            that.getBorrowList();
        } else {
            wx.showToast({
                title: '没有更多数据了',
                duration: 2000,
                icon: 'none'
            });
        }
    },

})